<template>
	<view style="width: 100vw;height: 100vh;" class="bg-white">
		<scroll-view scroll-y="true" style="width: 100%;height: 100%;">
			<!-- 顶部按钮 -->
			<view class="cu-custom" :style="[{height:CustomBar + 'px'}]">
				<view class="cu-bar fixed flex justify-between align-center bg-white"
					:style="{height:CustomBar+'px',paddingTop:StatusBar+'px'}" style="font-size: 32rpx;">
					<text class=" cuIcon-back margin-left" @click="back" style="font-size: 40rpx;"></text>
					<text class=" text-blue margin-right" @click="send()">发布</text>
				</view>
			</view>
			<!-- 讲书标题 -->
			<view style="margin-top: 24rpx; padding: 0 32rpx; line-height: 64rpx;">
				<textarea v-model="journal.title" style="color: #131415;font-size: 40rpx;font-weight: bold;" auto-height
					placeholder="请输入讲书标题（5-30个字）*" maxlength="30"
					placeholder-style="font-size: 40rpx;color: #aa5500;" />
			</view>
			<!-- 讲书描述 -->
			<view style="margin-top: 40rpx; padding: 0 32rpx; line-height: 64rpx;">
				<textarea v-model="journal.description" style="color: #131415;font-size: 40rpx;font-weight: bold;"
					auto-height placeholder="请输入讲书描述*" />
			</view>
			<!-- 讲书内容 -->
			<jinEdit placeholder="请输入课程内容(富文本编辑) *" :html="journal.content" @editOk="editOk" :uploadFileUrl="uploadUrl"
				ref="jinEdit">
			</jinEdit>
			<!-- 添加好物 -->
			<view @click="addGoodsLink" style="margin-top: 24rpx; margin-bottom: 80rpx; padding: 0 32rpx;"
				class="flex align-center justify-between">
				<view class="flex align-center">
					<text class="cuIcon-goods text-blue" style="font-size: 40rpx;"></text>
					<text style="font-size: 30rpx; margin-left: 20rpx;">添加好物链接（可选）</text>
				</view>
				<view class="cuIcon-right text-blue" style="font-size: 38rpx;"></view>
			</view>
			<!-- 音频上传 -->
			<view style="padding: 32rpx;">
				<lsj-upload ref="lsjUpload" width="200rpx" height="100rpx" childId="upload" :size="10" @input="onInput"
					@callback="onCallback">
					<view class="btn" style="height: 100rpx;">选择音频上传</view>
				</lsj-upload>
				<view class="flex  align-center "
					style="margin-top: 40rpx; background-color: #cacaca;border-radius: 20rpx;padding-right: 10rpx;padding-left: 10rpx;">
					<input type="text" v-model="journal.musicFile" disabled
						style="font-size: 30rpx;height: 60rpx;flex: 1;">
					<text class='cuIcon-roundclose' style="font-size: 40rpx;" @click="deleteMusic()"></text>
				</view>
			</view>
			<!-- 视频上传 -->
			<view style="padding: 32rpx;">
				<uni-file-picker fileMediatype="video" mode="list" limit="1" :auto-upload="false" @select="selectVideo"
					:value="journal.videoName?[{name:journal.videoName}]:[]" @delete="deleteVideo" title="请选择本节视频"
					:list-styles="listStyles">
				</uni-file-picker>
			</view>
			<!-- 封面上传 -->
			<view style="margin-top: 15rpx; padding: 0 32rpx; ">
				<uni-file-picker fileMediatype="image" mode="grid" limit="1" :auto-upload="false" @select="selectCover"
					:value="journal.cover?[{url:journal.cover}]:[]" @delete="deleteCover" title="最多选择1张封面图"
					:image-styles="{height:'200rpx', width: '200rpx'}">
				</uni-file-picker>
			</view>
			<!-- 标签选择 -->
			<view class="cu-form-group">
				<view class="title">标签选择</view>
				<view class="picker" @click="openSelect">
					请选择<text class="cuIcon-right"></text>
				</view>
			</view>
			<tki-tree ref="tree" :range="range" rangeKey="title" :multiple="true" @confirm="confirm"
				confirmColor="#4e8af7" />
			<!-- 占位区 -->
			<view style="width: 100%;height: 120rpx;"></view>
		</scroll-view>
	</view>
</template>

<script>
	import tkiTree from "../../components/tki-tree/tki-tree.vue"
	import jinEdit from '../../components/jin-edit/jin-edit.vue'
	export default {
		components: {
			jinEdit,
			tkiTree
		},
		data() {
			return {
				range: [], //多选	
				uploadUrl: "http://xuewenbao.cn:38880/xwb/edu/file/uploadOSS",
				listStyles: {
					// 是否显示边框
					border: true,
					// 是否显示分隔线
					dividline: true,
					// 线条样式
					borderStyle: {
						width: 1,
						color: 'blue',
						radius: 2
					}
				},
				journal: {
					userId: this.$store.getters.userid ? this.$store.getters.userid : "1",
					classArray: [], //标签数组，数据回显
					videoName: "", //视频名字,数据回显
					musicFile: "", //音频名字，数据回显
					title: "",
					description: "", //讲书描述
					content: "", //讲书内容（富文本）
					audio: "",
					video: "",
					cover: "",
					goodVo: null,
					subjectList: []
				}
			}
		},
		onLoad() {
			// 根据本地存储回显
			if (uni.getStorageSync('journal')) {
				this.journal = uni.getStorageSync('journal')
				
			}
			//获取分类
			this.getSubject().then(res => {
				Promise.all(this.getChildSubject(res)).then(res2 => {
					this.range = res2
					if (this.range && this.journal.classArray) {
						//寻找已被选中的标签,并进行数据回显
						this.journal.classArray.forEach(item => {
							if (item.parents.length == 0) {
								// 寻找一级分类
								let first = this.range.find(el => {
									return el.id == item.id
								})
								first.checked = true
							} else if (item.parents.length == 1) {
								// 寻找二级分类
								let first = this.range.find(el => {
									return el.id == item.parents[0].id
								})
								let second = first.children.find(el => {
									return el.id == item.id
								})
								second.checked = true
							} else {
								// 寻找三级分类
								let first = this.range.find(el => {
									return el.id == item.parents[0].id
								})
								let second = first.children.find(el => {
									return el.id == item.parents[1].id
								})
								let third = second.children.find(el => {
									return el.id == item.id
								})
								third.checked = true
							}
						})
						// console.log(this.range)
					}
				})
			})
		},
		onShow() {
			//获取好物链接
			if (uni.getStorageSync('goods')) {
				this.journal.goodVo = uni.getStorageSync('goods')
				this.$tip.success('链接添加成功')
			}
			else{
			  this.journal.goodVo=null	
			}
			this.$nextTick(()=>{
				this.onCreate()
				
			})
		},
		onHide() {
			this.$refs.lsjUpload.close();
	
		},
		methods: {
			confirm(e) {
				this.journal.classArray = e
				e.forEach(item => {
					this.journal.subjectList.push(item.id)
				})
				console.log(this.journal.classArray)
			},
			openSelect() {
				this.$refs.tree._show()
			},
			//获取一级分类
			getSubject() {
				return new Promise((resolve, reject) => {
					this.$http.get('/edu/onesubject/getAllOneSubject').then(res => {
						resolve(res.data.result)
					})
				})
			},
			// 获取子分类
			getChildSubject(array) {
				let proArray = [];
				for (let i = 0; i < array.length; i++) {
					proArray.push(new Promise((resolve, reject) => {
						this.$http.get('/edu/child-subject/getAllChildSubject/' + array[i].id).then(res => {
							let {
								result
							} = res.data
							result.forEach(val => {
								val.children = val.subjectVoList
								delete val.subjectVoList
							})
							array[i].children = result
							resolve(array[i])
						})
					}))
				}
				return proArray;
			},
			onCreate() {
				// 初始化参数并创建上传DOM
				this.$refs.lsjUpload.create({
					// #ifdef APP-PLUS
					cuWebview: this.$mp.page.$getAppWebview(), // app必传
					// #endif
					url: 'http://xuewenbao.cn:38880/xwb/edu/file/uploadOSS', //替换为你的接口地址
					name: 'file', // 附件key
					size: 10, // 附件上传大小上限(M)，默认10M
					debug: true,
					//根据你接口需求自定义请求头
					header: {
						'Authorization': 'token'
					},
					//根据你接口需求自定义body参数
					formData: {
						'orderId': 1000
					}
				});
			},
			onInput(e) {
				this.$tip.loading('上传中')
			},
			onCallback(e) {
				this.journal.musicFile = e.fileName
				this.journal.audio = JSON.parse(e.responseText).message
				this.$tip.loaded()
				this.$tip.success('上传成功')
			},
			addGoodsLink() {
				this.$refs.jinEdit.release()
				// 保存本地存储方便数据回显
				uni.setStorageSync('journal', this.journal)
				this.$Router.push({
					name: 'addGoodsLink'
				})
			},
			deleteMusic(e) {
				if (this.journal.audio== "") {
					return;
				}
				this.$http.post('/edu/file/deleteOss', this.journal.audio).then(res => {
					if (res.data.success) {
						this.$tip.success('删除成功')
						this.journal.audio = ""
						this.journal.musicFile = ""
					}
				})
			},
			deleteVideo(e) {
				if (this.journal.video == "") {
					return;
				}
				this.$http.post('/edu/file/deleteOss', this.journal.video).then(res => {
					if (res.data.success) {
						this.$tip.success('删除成功')
						this.journal.video = ""
						this.journal.videoName = ""
					}
				})
			},
			deleteCover(e) {
				if (this.journal.cover == "") {
					return;
				}
				this.$http.post('/edu/file/deleteOss', this.journal.cover).then(res => {
					if (res.data.success) {
						this.$tip.success('删除成功')
						this.journal.cover = ""
					}
				})
			},
			send() {
				this.$refs.jinEdit.release()
				console.log(this.journal)
				this.$http.post('/edu/book/addBook', this.journal).then(res => {
					console.log(res)
					if (res.data.success) {
						uni.removeStorageSync('goods')
						uni.removeStorageSync('journal')
						this.$tip.success('讲书创作成功!');
						this.$Router.replaceAll({
							name: 'createCenter'
						})
					}
				})
			},
			async selectVideo(e) {
				console.log(e)
				uni.showLoading({
					title: '正在上传中...'
				})
				for (let temp of e.tempFiles) {
					// 图片上传服务器
					await uni.uploadFile({
						url: this.uploadUrl,
						filePath: temp.path,
						name: "file",
						formData: {
							'biz': 'video'
						},
						success: res => {
							//上传完成后处理
							let data = JSON.parse(res.data)
							if (data.success) {
								this.journal.video = data.message
								this.journal.videoName = temp.name
								console.log(this.journal.videoName)
							} else {
								console.log("video上传失败", data.message)
							}
							uni.hideLoading()
						},

					});
				}
			},
			async selectCover(e) {
				console.log(e)
				uni.showLoading({
					title: '正在上传中...'
				})
				for (let temp of e.tempFiles) {
					// 图片上传服务器
					await uni.uploadFile({
						url: this.uploadUrl,
						filePath: temp.path,
						name: "file",
						formData: {
							'biz': 'cover'
						},
						success: res => {
							//上传完成后处理
							let data = JSON.parse(res.data)
							if (data.success) {
								this.journal.cover = data.message
								// console.log(this.cover)
							} else {
								console.log("上传失败", data.message)
							}
							uni.hideLoading()
						},

					});
				}
			},
			editOk(e) {
				this.journal.content = e.html
			},
			back() {
				uni.removeStorageSync('goods')
				uni.removeStorageSync('journal')
				this.$Router.push({
					name: 'createCenter'
				})
			}
		}
	}
</script>

<style>
	.btn {
		height: 80rpx;
		background-color: #007AFF;
		color: #fff;
		border-radius: 10rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 28rpx;
	}
</style>
